package com.coder.algorithm.offer_2;

import java.util.Arrays;

/**
 * 数组中数组和下标相等的元素
 *
 * @author yuhushuan
 * @date 2020/6/30 07:51
 */
public class _53_3_IntegerIdenticalToIndex {
    private static int getNumberSameAsIndex(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return -1;
        }
        int left = 0;
        int right = numbers.length - 1;
        while (left <= right) {
            int middle = (left + right) >> 1;
            if (numbers[middle] == middle) {
                return middle;
            } else if (numbers[middle] > middle) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        // 功能测试
        // 数组包含此元素 3
        print(new int[]{-3, -1, 1, 3, 5});
        // 数组中不包含此元素
        print(new int[]{-3, -1, 1, 2, 5});

        //边界值测试
        // 只有一个数字
        print(new int[]{1});
        // 位于开头 0
        print(new int[]{0, 2, 4, 6});
        // 位于结尾 4
        print(new int[]{-4, -2, 0, 2, 4});

        print(null);
    }

    private static void print(int[] numbers) {
        System.out.println("数组：" + Arrays.toString(numbers));
        System.out.println("数字和下标相同的数字为：" + getNumberSameAsIndex(numbers));
        System.out.println();
    }
}
